package isr.cloudgate.dashboard.servlet;

import isr.google.gdata.GDataClient;
import isr.google.gdata.data.GoogleNickname;

import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class NicknameServlet
 */
public class NicknameServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(NicknameServlet.class
		.getName());
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("nickname request (post)");

		GDataClient client = null;

		try {
			String userId = request.getParameter("user");
			if (userId == null) {
				logger.warning("no user parameter found in nickname request");
				return;
			}

			client = ServletUtilities.getAppsClient(request);
			if (client == null) {
				logger.warning("no apps client");
				return;
			}

			Collection<GoogleNickname> nicknames = client.getNicknames(userId);
			request.setAttribute("userId", userId);
			request.setAttribute("nicknames", nicknames);

			logger.info(String.format("nicknames for user '%s': %s", userId,
				nicknames));

		} catch (Exception e) {

			logger.warning(e.toString());
			request.setAttribute("userMessage", e.toString());

		}

		request.getRequestDispatcher(JspPage.nicknames).forward(request,
			response);

	}

}
